package com.aosan.website.auth.config

import org.slf4j.LoggerFactory
import org.springframework.security.jwt.JwtHelper
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken
import org.springframework.security.oauth2.common.OAuth2AccessToken
import org.springframework.security.oauth2.provider.OAuth2Authentication
import org.springframework.security.oauth2.provider.token.TokenEnhancer
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
import java.util.*


class JwtTokenEnhancer : TokenEnhancer {

    private val logger = LoggerFactory.getLogger(this::class.java)

    override fun enhance(accessToken: OAuth2AccessToken, authentication: OAuth2Authentication): OAuth2AccessToken {
        val result = DefaultOAuth2AccessToken(accessToken)
        val info: MutableMap<String, Any?> = LinkedHashMap(accessToken.additionalInformation)
        var tokenId = result.value
        if (!info.containsKey(JwtAccessTokenConverter.TOKEN_ID)) {
            info[JwtAccessTokenConverter.TOKEN_ID] = tokenId
        } else {
            tokenId = info[JwtAccessTokenConverter.TOKEN_ID] as String?
        }
        result.additionalInformation = info
//        result.value = encode(result, authentication)
        return result
    }

//    protected fun encode(accessToken: OAuth2AccessToken?, authentication: OAuth2Authentication?): String? {
//        val content: String
//        content = try {
//            objectMapper.formatMap(tokenConverter.convertAccessToken(accessToken, authentication))
//        } catch (e: Exception) {
//            throw IllegalStateException("Cannot convert access token to JSON", e)
//        }
//        return JwtHelper.encode(content, signer).encoded
//    }

}